package com.second.system.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.second.common.pojo.Role;
import com.second.common.pojo.UserRole;
import com.second.system.dao.RoleDao;
import com.second.system.dao.UserRoleDao;
import com.second.system.service.RoleService;
import com.second.system.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: second-education-parent
 * @description:
 * @author: 王子朋
 * @create: 2023-05-24 19:44
 **/
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;
    @Override
    public List<Role> findAll() {
        return roleDao.selectList(null);
    }

    @Override
    public List<Role> findByUserId(String userId) {
        List<Role>  roles=roleDao.selectByUserId(userId);
        return roles;
    }

    @Override
    public Integer confirm(String userId, String[] roleIds) {
        //删除该用户具有的角色
        roleDao.deleteByUserId(userId);
        //批量添加用户角色
        List<UserRole> userRoleList = Arrays.stream(roleIds).map(roleId -> new UserRole(IdUtil.getSnowflakeNextId()+"", roleId, userId, 0, LocalDateTime.now(), LocalDateTime.now())).collect(Collectors.toList());
        userRoleDao.batchInsert(userRoleList);
        return null;
    }

    @Override
    public Page<Role> list(Integer current, Integer pageSize, RoleVo roleVo) {
        Page<Role> page = new Page<>(current, pageSize);
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(roleVo.getName())){
            wrapper.like("role_name",roleVo.getName());
        }
        if (roleVo.getStatus()!=null){
            wrapper.eq("is_deleted",roleVo.getStatus());
        }
        Page<Role> page1 = roleDao.selectPage(page, wrapper);
        return page1;
    }

}
